import api
from DBAction import DBAction

# 这个会返回期数和对应的日期
# url = 'https://pocketapi.48.cn/gift/api/v1/melee/rank/getMeleeRankPage'
# params = {"rankid": rankid}

# POST https://pocketapi.48.cn/gift/api/v1/melee/rank/getMeleeYearRankPage HTTP/1.1


def getrank(rankid, params=None):
    url = 'https://pocketapi.48.cn/gift/api/v1/melee/rank/getMeleeWeekRank'
    if params is None:
        params = {"rankId": rankid}
        # params = {"token": global_config.POCKET48_TOKEN} 这个会返回期数和对应的日期
    # 取往期的，添加参数{"rankid":141}  141是21年0426到0502的
    # 根据nextid一直取，直到rankUserList长度为零
    api.wait_random_time(5)
    print(url, params)
    response = api.post(url, params)
    print(response)

    if response['status'] == 200:
        for data in response['content']['rankUserList']:
            userid = data['baseUserInfo']['userId']
            rankNum = data['rankNum']
            melee = data['melee']

            result = db.data_inquiry_all('select count(1) from member where memberid=%s', userid)
            if result[0][0] == 0:
                name = data['baseUserInfo']['nickname']
                db.data_operate("insert into member(memberid,name) values(%s,%s)",
                                (userid, name))
                print(name)

            sql = 'insert into ranks values(%s, %s, %s, %s)'
            db.data_operate(sql, (userid, rankNum, melee, rankid))
        if len(response['content']['rankUserList']) > 0:
            params = {"nextId": response['content']['nextId'], "rankId": rankid}
            getrank(rankid, params)


if __name__ == '__main__':
    # api.start_schedule()
    db = DBAction('pocket48')
    config = api.getconfig()
    rankid = config.getint('member', 'rankid')
    getrank(rankid)
